using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class MaterialUtilityWindow : EditorWindow {
 
    static  List<MeshRenderer> itemList = new List<MeshRenderer>();

    private Vector2 m_ScrollPos = Vector2.zero;

    [MenuItem("Window/ViNo/MaterialUtilityWindow")]
    public static void Init(){
        EditorWindow.GetWindow(typeof(MaterialUtilityWindow));
    }
 
    void OnGUI(){
		EditorGUILayout.HelpBox ("Select a game object in hierarchy view", MessageType.Info);

		if (GUILayout.Button("Show Materials" ))
        {            

           itemList = new List<MeshRenderer>();

           MeshRenderer[] buttons = Selection.activeGameObject.GetComponentsInChildren<MeshRenderer>() as MeshRenderer[];
           for(int i=0;i<buttons.Length;i++){
                TextMesh tm = buttons[ i ].gameObject.GetComponent<TextMesh>();
                if( ! tm ){
                    itemList.Add( buttons[ i ] );
                }
           }
           Selection.objects = itemList.ToArray();
        }

        // ---------------------------------.
            GUICommon.DrawLineSpace( 5f , 5f );
        // ---------------------------------.

        m_ScrollPos = EditorGUILayout.BeginScrollView( m_ScrollPos );
        {
            foreach( MeshRenderer ren in itemList ){
    			if ( ren == null) {
    				continue;
    			}

                EditorGUILayout.BeginHorizontal();

                if( ren.sharedMaterial != null ) {
                    ren.sharedMaterial.mainTexture = EditorGUILayout.ObjectField( ren.sharedMaterial.mainTexture , typeof(Texture2D) , false , GUILayout.Width( 64f) , GUILayout.Height( 64f ) ) as Texture2D;
                }

                EditorGUILayout.BeginVertical();
                {
                    if( ren.sharedMaterial != null ) {
                        EditorGUILayout.BeginHorizontal();

                            EditorGUILayout.LabelField( "Material" , GUILayout.Width( 50f ) );
                            ren.sharedMaterial = EditorGUILayout.ObjectField( ren.sharedMaterial , typeof(Material) , false , GUILayout.Width( 125f ) ) as Material;

                        EditorGUILayout.EndHorizontal();
                    }                

                    if( GUILayout.Button( ren.name ) ){
                        Selection.activeGameObject = ren.gameObject;
                    }
                }
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
            }     
        }
        EditorGUILayout.EndScrollView();   

    }
}